#!/usr/local/bin/ruby
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'utf8'

# Add Event for listening:
#   Create a new Thread for Event
# opts Format:
#     s/r     :single/repeat
#     alarm[s]
#       alarm1-waiting-time
#       alarm1-tip
#       alarm2-waiting-time
#       alarm2-tip
#       ......
def addEvent(opts, doIt)
  isRepeat = (opts[0] =~ /\Ar(epeat)?\Z/i)!=nil
  beginIndex = opts.length%2 == 0 ? 0:1
  alarms = opts[beginIndex..-1]
  thread = Thread.new(isRepeat, alarms, doIt) do |isRepeat, alarms, doIt|
    if isRepeat
      loop {runAlarms(alarms, doIt)}
    else
      runAlarms(alarms, doIt)
    end
  end
  thread.join
end

# Parse time to seconds
# time * 60
def timeToSeconds(time)
  time.to_f*60
end

# Run each alarm by makeTip block
def runAlarms(alarms, makeTip)
  size = alarms.length / 2
  (0...size).each do |i|
    time = alarms[i*2]
    tip = alarms[i*2+1]
    sleep(timeToSeconds(time))
    makeTip.doIt tip
  end
end

